﻿using System;
using System.Collections.ObjectModel;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.ServiceModel.Description;
using System.ServiceModel.Dispatcher;

namespace WcfRestService1.ExceptionHandling
{
    [AttributeUsage(AttributeTargets.Class, Inherited = true)]
    public class ErrorHandlerBehaviorAttribute : Attribute, IServiceBehavior
    {
        public readonly GeneralErrorHandler ErrorHandler;

        public ErrorHandlerBehaviorAttribute()
        {
            ErrorHandler = new GeneralErrorHandler(error =>
            {
                //...在这里记录并处理异常
                return false; //返回false, 以使其他处理异常的方法代理能继续处理这个异常.
            },

            error => new SampleItem //在这里, 我们返回异常的Message. 实际情况下的处理可能会很复杂, 取决于你的需求.
            {
                Id = 20110509,
                StringValue = error.Message
            });
        }

        #region IServiceBehavior Members

        public void AddBindingParameters(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase,
            Collection<ServiceEndpoint> endpoints, BindingParameterCollection bindingParameters)
        { }

        public void ApplyDispatchBehavior(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)
        {
            //在这里注册我们的GeneralErrorHandler
            foreach (ChannelDispatcher dispatcher in serviceHostBase.ChannelDispatchers)
                dispatcher.ErrorHandlers.Add(ErrorHandler);
        }

        public void Validate(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)
        { }

        #endregion
    }
}